package com.itzyf.pokemondata.activity

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.itzyf.pokemondata.BuildConfig
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.activity.gallery.NewGalleryActivity
import com.itzyf.pokemondata.activity.illustration.IllustrationActivity
import com.itzyf.pokemondata.activity.panel.DataPanelActivity
import com.itzyf.pokemondata.activity.rank.RankListActivity
import com.itzyf.pokemondata.activity.setting.AboutAppActivity
import com.itzyf.pokemondata.activity.setting.RewardActivity
import com.itzyf.pokemondata.activity.team.TeamActivity
import com.itzyf.pokemondata.adapter.MenuAdapter
import com.itzyf.pokemondata.bean.MainDo
import com.itzyf.pokemondata.service.DataIntentService
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.tydic.baselibrary.activity.BaseActivity
import com.tydic.baselibrary.utils.DividerGridItemDecoration
import kotlinx.android.synthetic.main.activity_main.*
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : BaseActivity() {
    private val sdf = SimpleDateFormat("yyyyMM", Locale.CHINESE)
    private var receiver: LoadingBroadcast? = null
    override fun handlerActivity() {
        val mainList = mutableListOf(
            MainDo("数据面板", R.drawable.ic_data, DataPanelActivity::class.java),
            MainDo("队伍预设", R.drawable.ic_team, TeamActivity::class.java),
            MainDo(
                "图鉴大全", R.drawable.ic_resource_icon,
                IllustrationActivity::class.java
            ),
            MainDo(
                "综合大全",
                R.drawable.ic_image,
                NewGalleryActivity::class.java
            ),
            MainDo(
                "存钻记录",
                R.drawable.ic_diamond,
                DrillRecordActivity::class.java
            ),
            MainDo(
                "高级狩猎场",
                R.drawable.ic_hunting,
                HuntingGroundActivity::class.java
            ),
            MainDo(
                "伤害计算器",
                R.drawable.ic_caculation,
                DamageCalculationActivity::class.java
            ),
            MainDo(
                "精灵价格表",
                R.drawable.ic_price,
                PriceActivity::class.java
            ),
            MainDo("各项排行榜", R.drawable.ic_rank, RankListActivity::class.java),
            MainDo(
                "节日使者Q&A",
                R.drawable.ic_icon_answer_hover,
                FestivalEnvoyActivity::class.java
            ),
            MainDo(
                "突破资源计算",
                R.drawable.ic_resource_icon,
                DiscountActivity::class.java
            ),
            MainDo(
                "属性克制计算",
                R.drawable.ic_resistance,
                ResistanceActivity::class.java
            ),
            MainDo(
                "礼包码",
                R.drawable.ic_code,
                CodeActivity::class.java
            ),
            MainDo(
                "版本更新记录",
                R.drawable.ic_history_black_24dp,
                HistoryActivity::class.java
            ),
            MainDo(
                "打赏作者",
                R.drawable.ic_money,
                RewardActivity::class.java
            ),
            MainDo(
                "设置",
                R.drawable.ic_settings_gray_24dp,
                AboutAppActivity::class.java
            )
        )
        disableBackButton()

        receiver = LoadingBroadcast()
        val intentFilter = IntentFilter()
        intentFilter.addAction("loading")
        registerReceiver(receiver, intentFilter)

        var adapter = MenuAdapter(R.layout.item_main, mainList)
        if (sp.getBoolean("main", true)) {
            rv_list.layoutManager = GridLayoutManager(this, 3) as RecyclerView.LayoutManager?
            adapter = MenuAdapter(R.layout.item_main2, mainList)
        }

        startService(Intent(this, DataIntentService::class.java))
        rv_list.adapter = adapter
        rv_list.addItemDecoration(DividerGridItemDecoration(this))
        adapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(this@MainActivity, mainList[position].clazz)
            startActivity(intent)
        }

        //固定月底提示一波
        val c = Calendar.getInstance()
        //每个月25号之后弹一次
        if (sdf.format(Date()) != sp.getString("yyyyMM", "")
            && c.get(Calendar.DAY_OF_MONTH) > 26
        ) {
            showReward()
        }
        if (sp.getInt("VERSION_CODE", 0) < BuildConfig.VERSION_CODE)
            showVersionNote()
    }


    private fun showReward() {
        sp.edit().putString("yyyyMM", sdf.format(Date())).apply()
        showAlertDialog(
            "打赏", "制作不易，打赏一波可好", "打赏"
        ) { _, _ ->
            startActivity(Intent(this, RewardActivity::class.java))
        }
    }

    /**
     * 更新内容
     */
    private fun showVersionNote() {
        sp.edit().putInt("VERSION_CODE", BuildConfig.VERSION_CODE).apply()
        AlertDialog.Builder(this@MainActivity)
                .setTitle("更新内容")
                .setMessage("1.高级狩猎场，礼包码转移到自建服务器\n" +
                        "2.增加精灵价格表（综合大全里的不在维护）\n" +
                        "3.更新基础数据")
                .setPositiveButton("关闭", null)
                .show()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (receiver != null) {
            unregisterReceiver(receiver)
        }
    }

    override fun getContentViewId() = R.layout.activity_main

    override fun getToolbarTitle(): String = getString(R.string.app_name)


    override
    fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.switch1, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        item?.let {
            when (it.itemId) {
                R.id.action_switch -> {
                    val tip = if (sp.getBoolean("main", true)) "列表" else "九宫格"
                    val builder = QMUIDialog.MessageDialogBuilder(this)
                        .setMessage("是否切换成${tip}布局？")
                        .setTitle("提示")
                        .addAction("取消") { dialog, _ ->
                            dialog.dismiss()
                        }
                        .addAction(
                            "确定"
                        ) { dialog, _ ->
                            sp.edit().putBoolean("main", !sp.getBoolean("main", true)).apply()
                            showToast("重启后生效")
                            dialog.dismiss()
                        }
                    builder.show()

                }
                else -> {
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }


    inner class LoadingBroadcast : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.let {
                if (it.getStringExtra("notice") == "notice") {
                    if (sp.getString("notice", "") != "") {
                        tvNotice.text = sp.getString("notice", "")
                        tvNotice.visibility = View.VISIBLE
                        tvNotice.setOnClickListener {
                            showAlertDialog("公告", sp.getString("notice", ""), "确定", null)
                        }
                    }
                    return
                }
                if (it.getIntExtra("loading", -1) != -1) {
                    showProgressDialog()
                } else {
                    dismissProgressDialog()
                }
            }
        }

    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        val tag = intent.getStringExtra("EXIT_TAG")
        if (tag != null && !TextUtils.isEmpty(tag)) {
            if ("SINGLETASK" == tag) { //退出程序
                finish()
            }
        }
    }
}
